<?php


namespace app\api\controller;

use app\api\model\Cart as CartModel;

class Cart extends BaseController
{

    /**
     * 获取购物车内所有商品
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCartAll()
    {

        $user_id = 1;
        $res = CartModel::all(function ($query) use ($user_id) {
            $query->with('goodsspecs')
                ->where(['user_id' => $user_id]);
        });

        // $user_id = session('user');
        // $user_id = 1;
        // $data = new CartModel();
        // $res = $data->getCartAll($user_id);
        return $this->renderSuccess(compact('res'));
    }

    /**
     * 加入购物车
     * @param int $goodsId 商品id
     * @param string $goodsSkuId 商品sku索引
     * @param int $goodsNum 商品数量
     * @return array|\think\response\Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $user_id = 1;
        $data = $this->request->param();
        $model = new CartModel;
        $data['goods_id'] = 3;
        $data['goods_sku_id'] = 1;
        $data['pro_num'] = 2;
        // if (!$model->joinCart($user_id, $data['goods_id'], $data['goods_sku_id'], $data['pro_num'])) {
        //     return $this->renderError($model->getError() ?: '加入购物车失败');
        // }
        $res = $model->joinCart($user_id, $data['goods_id'], $data['goods_sku_id'], $data['pro_num']);
        // var_dump(db('cart')->getLastSql());
        return $this->renderSuccess(compact('res'), '加入购物车成功');
    }

    /**
     * 购物车删除商品
     *
     *
     * $goods_sku_id  商品规格id
     */
    public function delete()
    {
        $goods_sku_id = $this->request->param();
        $user_id = session('user_id');
        $user_id = 1;
        $ids = [1, 2];
        foreach ($ids as $v) {
            $res = db('cart')->where(['goods_sku_id' => $v, 'user_id' => $user_id])->delete();
        }
        return $this->renderSuccess(compact('res'));
        // !empty($cartIds) && $where[] = ['id', 'in', $cartIds];

    }
}